﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;

namespace Gomoku
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        
        int gameMode = 0;
        // 0 - 双人对战
        // 1 - 人机对战
        private void 开始SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigForm fc = new ConfigForm();
            fc.ShowDialog();
            if (fc.isStart)
            {
                gameMode = fc.gameMode; //读取游戏模式
                isStart = true;
                SetStatus("游戏开始", StatusType.Message);
                listBox1.Items.Insert(0, "游戏开始 - " + (fc.gameMode == 0 ? "双人对战" : "人机对战"));
                GameStart();
            }
        }

        string[] letters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O" };
        GameDraw gd;
        SoundPlayer player;
        bool isStart = false;
        private void mainForm_Load(object sender, EventArgs e)
        {
            gd = new GameDraw(gameMap);
            gd.Initialize(GlovalVar.Lines); //初始化游戏（绘制棋盘等）

            player = new SoundPlayer();
            player.SoundLocation = Application.StartupPath + @"\audio\down.wav";
            try
            {
                player.Load();
            }
            catch (Exception)
            {
                MessageBox.Show("没有找到落子声音文件, 请检查文件是否齐全!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }

        int now = 0;
        // 0 - 白方
        // 1 - 黑方
        //开始游戏后，默认白方先手
        Gomoku map; //全局棋盘变量
        void GameStart()
        {
            gameMap.Cursor = Cursors.Hand;
            gd = new GameDraw(gameMap);
            gd.Initialize(GlovalVar.Lines); //初始化游戏（绘制棋盘等）
            map = new Gomoku(GlovalVar.Lines);
            switch (gameMode)
            {
                case 0:
                    gamemode_label.Text = "双人对战";
                    now = 0;
                    break;
                case 1:
                    gamemode_label.Text = "人机对战";
                    now = 0;
                    break;
            }
            RefreshNow();
        }
        private void gameMap_MouseDown(object sender, MouseEventArgs e)
        {
            if (!isStart)
            {
                return;
            }
            int x = e.X, y = e.Y;
            int chessX = 0, chessY = 0;
            int a = 640 / (GlovalVar.Lines + 1);
            chessX = (x - a / 2) / a;
            chessY = (y - a / 2) / a; //获取在棋盘中的坐标
            if (chessX >= GlovalVar.Lines || chessY >= GlovalVar.Lines)//最后超出边框一半
            {
                return;
            }

            if (map.GetChessStatus(chessX, chessY) == ChessStatus.None)
            {
                if (now == 0)
                {
                    gd.DrawChess(chessX, chessY, 0);
                    map.SetChessStatus(chessX, chessY, ChessStatus.White);
                    playSound();
                    SetStatus("白方落子(" + letters[chessX] + ", " + (chessY + 1) + ")", StatusType.Message);
                    listBox1.Items.Insert(0, "白方落子(" + letters[chessX] + ", " + (chessY + 1) + ")");
                    GameStatus gs = map.GetIsSuccessful();
                    if (gs.IsSuccessful)
                    {
                        gd.DrawSuccessLine(gs.StartPosition, gs.EndPosition);
                        isStart = false;
                        gameMap.Cursor = Cursors.Default;
                        //MessageBox.Show(gs.StartPosition.X + " " + gs.StartPosition.Y + "\n" + gs.EndPosition.X + " " + gs.EndPosition.Y);
                        MessageBox.Show("白方胜利！", "Win", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    now = 1;
                    RefreshNow();
                    if (gameMode == 1)
                    {
                        AILabel.Text = "AI思考中";
                        Delay(1000); //因为这套代码AI太快，所以加点延迟制造效果
                        AILabel.Text = "思考完毕";
                        AI ai = new AI(map.GetChessMap());
                        ChessPosition cp = ai.GetAIChessPosition();

                        gd.DrawChess(cp.X, cp.Y, 1);
                        playSound();
                        map.SetChessStatus(cp.X, cp.Y, ChessStatus.Black);
                        SetStatus("黑方落子(" + letters[cp.X] + ", " + (cp.Y + 1) + ")", StatusType.Message);
                        listBox1.Items.Insert(0, "黑方落子(" + letters[chessX] + ", " + (chessY + 1) + ")");
                        GameStatus gs2 = map.GetIsSuccessful();
                        if (gs2.IsSuccessful)
                        {
                            gd.DrawSuccessLine(gs2.StartPosition, gs2.EndPosition);
                            isStart = false;
                            gameMap.Cursor = Cursors.Default;
                            MessageBox.Show("黑方胜利！", "Win", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        now = 0;
                        RefreshNow();
                    }
                }
                else if (now == 1)
                {
                    gd.DrawChess(chessX, chessY, 1);
                    map.SetChessStatus(chessX, chessY, ChessStatus.Black);
                    playSound();
                    SetStatus("黑方落子(" + letters[chessX] + ", " + (chessY + 1) + ")", StatusType.Message);
                    listBox1.Items.Insert(0, "黑方落子(" + letters[chessX] + ", " + (chessY + 1) + ")");
                    GameStatus gs3 = map.GetIsSuccessful();
                    if (gs3.IsSuccessful)
                    {
                        gd.DrawSuccessLine(gs3.StartPosition, gs3.EndPosition);
                        isStart = false;
                        gameMap.Cursor = Cursors.Default;
                        MessageBox.Show("黑方胜利！", "Win", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    now = 0;
                    RefreshNow();
                }

            }
            else
            {
                SetStatus("这个位子已经有棋子了！", StatusType.Error);
            }
            void playSound()
            {
                if (游戏声音AToolStripMenuItem.Checked)
                {
                    player.Play();
                }
            }
        }
        void RefreshNow()
        {
            switch (now)
            {
                case 0:
                    who.Text = "白方";
                    break;
                case 1:
                    who.Text = "黑方";
                    break;
            }
        }
        void SetStatus(string StatusText, StatusType statusType)
        {
            toolStripStatusLabel1.Text = StatusText;
            if (statusType == StatusType.Message)
            {
                toolStripStatusLabel1.ForeColor = Color.Black;
            }
            else if (statusType == StatusType.Error)
            {
                toolStripStatusLabel1.ForeColor = Color.Red;
            }
        }
        enum StatusType
        {
            Message,
            Error
        }
        private void 游戏声音AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            游戏声音AToolStripMenuItem.Checked = !游戏声音AToolStripMenuItem.Checked;
        }
        private void 结束游戏XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        /// <summary>
        /// 无阻塞延迟，代码参考自网络
        /// </summary>
        /// <param name="milliSecond"></param>
        public static void Delay(int milliSecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) < milliSecond)
            {
                Application.DoEvents();
            }
        }

        private void 自动保存成功截图SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            自动保存成功截图SToolStripMenuItem.Checked = !自动保存成功截图SToolStripMenuItem.Checked;
        }
    }
}
